# -* - coding: UTF-8 -* -
#import sys 
#reload(sys)
#sys.setdefaultencoding('utf8')
#将队列分成高中低三个优先级
import string
import time 
from time import sleep
import os
import logging
from task import *
from base_thread import *
#提交任务到FastCGI
class ClientThread(Thread):  
	def __init__(self,client,queue_server,notify_center,service_center,durable,queue):  
		Thread.__init__(self) 
		self.client = client
		self.queue_server = queue_server
		self.durable =durable
		self.queue = queue		
		self.service_center=service_center
		self.notify_center = notify_center
			
	#取出任务发放
	def on_run(self):
		#logging.info("Transform Started:"+str(self)) 
		try:
			if not self.queue.empty():
				req_str = self.queue.get(timeout=1)# 获取队列 
				if req_str.startswith("{") and req_str.endswith("}"):
					try:
						#logging.info('get a message')
						data,command= self.process_message(req_str)
						logging.debug('['+self.queue_server.queue_name+','+command+']'+str(data))
					except Exception as e:
						logging.error('ClientThread.on_run')
						logging.exception(e)
				else:
					try:
						#logging.info('get a message')
						ret=self.client.send(req_str)
						logging.info(ret)
					except Exception as e:
						self.queue.put(req_str)
						logging.error('CGI:')
						logging.exception(e)
				#finally:
					#self.queue.task_done()
				#	print('finally')
		except:
			pass

	def process_message(self,body):
		ret=''
		task = Task.createFromJson(body)
		if task.checkSign() and task.checkTimes():
			self.notify_center.execute(task)
			
			if task.plan == 'loop_delay':#循环任务
				#没用直接使用Interval,执行也需要时间，这样更准确
				
				data=None
				if self.durable and self.durable.check(task):
					data=self.durable.read(task.uuid)

				if (data is None) or (data['status']==1):
					
					#通过FastCGI协议发送给php-fpm执行
					if self.service_center.check(task):
						ret = self.service_center.execute(task,self.queue)
					else:
						ret=self.client.send(task.toJson(),task.command)
					#更新状态
					if ( self.durable and data):
						self.durable.update(task.uuid,ret)
					#循环任务，再次进入队列
					if task.times > 0:
						args={
							'delivery_mode' : 2,
							'headers':{'x-delay':(task.next_time - int(time.time())) * 1000}
						}
						self.queue_server.send(task.toJson(),args)
					if (ret=='error'):
						self.queue.put(task.toJson())						
			else:
				data=None
				if  self.durable and self.durable.check(task):
					data=self.durable.read(task.uuid)
				if (data is None) or (data['status']==1):
					#通过FastCGI协议发送给php-fpm执行
					if self.service_center.check(task):
						ret = self.service_center.execute(task,self.queue)
					else:
						ret=self.client.send(task.toJson(),task.command)
					#更新状态
					if (self.durable and data):
						self.durable.update(task.uuid,ret);
					if (ret=='error'):
						self.queue.put(task.toJson())
		return ret,task.command


